<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="flowerSearch" class="demo-form-inline">

        <el-form-item>
          <el-input v-model="flowerSearch.flowerName" placeholder="鲜花名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="flowerSearch.flowerOrigin" placeholder="鲜花发源地"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="flowerSearch.attributeId" placeholder="鲜花种类">
            <el-option label="所有种类" value="0"></el-option>
            <el-option :label="f.attributeName" :value="f.attributeId" v-for="f in flowertypeList" :key="f.attributeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addFlower">添加鲜花</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="flowerList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="编号"
            align="center"
            prop="flowerId"
            width="180"/>
        <el-table-column
            label="名称"
            prop="flowerName"
            align="center"/>
        <el-table-column
            label="发源地"
            prop="flowerOrigin"
            align="center"/>
        <el-table-column
            label="价格"
            prop="flowerPrice"
            align="center"/>
        <el-table-column
            label="数量"
            prop="flowerQuantity"
            align="center"/>
        <el-table-column
            label="所属种类"
            prop="attributeName"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{flower}}
      <el-form :model="flower" :rules="rules" ref="ruleForm">
        <el-form-item label="鲜花名称" prop="flowerName" :label-width="formLabelWidth">
          <el-input v-model="flower.flowerName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="鲜花发源地" prop="flowerOrigin" :label-width="formLabelWidth">
          <el-input v-model="flower.flowerOrigin" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="鲜花价格" prop="flowerPrice" :label-width="formLabelWidth">
          <el-input v-model.number="flower.flowerPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="鲜花数量" prop="flowerQuantity" :label-width="formLabelWidth">
          <el-input v-model="flower.flowerQuantity" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所属种类" prop="attributeId" :label-width="formLabelWidth">
          <el-select v-model="flower.attributeId" placeholder="请选择种类">
            <el-option label="所有种类" value="0"></el-option>
            <el-option :label="f.attributeName" :value="f.attributeId" v-for="f in flowertypeList" :key="f.attributeId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveFlower">保 存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import flowerApi from "@/api/flower"
import flowertypeApi from "@/api/flowertype";

export default {
  data() {

    let checkPrice = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('价格不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('价格必须为数字值'))
      } else if (value < 1) {
        return callback(new Error('必须在大于1'))
      } else {
        callback()
      }
    }


    return {
      flowerList: [],
      page: 1,
      pageSize: 5,
      total: 100,
      flowerSearch: {},
      flowertypeList: [],
      dialogFormVisible: false,
      flower: {},
      title: '添加花花',
      formLabelWidth: '100px',
      multipleSelection:[],
      flowerIds: [],

      rules: {

        flowerName: [
          {required: true, message: '请输入花朵名称', trigger: 'blur'},
        ],
        flowerOrigin: [
          {required: true, message: '请选择发源地', trigger: 'blur'},
        ],

        flowerPrice: [

          { validator : checkPrice, trigger: 'blur'}
        ],

        flowerQuantity: [
          {required: true, message: '请输入花朵数量', trigger: 'blur'},
        ],

        attributeId: [
          {required: true, message: '请选择花朵属性', trigger: 'blur'},
        ]
      }
    }
  }
  ,
  created() {

    this.search()
    this.findAllFlowertype()
  },
  methods: {

    async findFlowers() {
      const {data: res} = await flowerApi.findAllFlower()
      console.log(res)
      if (data.code === 200) {
        this.flowerList = res.data.list
      }
    },

    async findByPage() {
      const {data: res} = await flowerApi.findByPage(this.page, this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.flowerList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },

    async findAllFlowertype() {

      const {data: res} = await flowertypeApi.findAllFlowertype()
      console.log(res)
      if (res.code === 200) {
        this.flowertypeList = res.data.list
      }
    },

    async search() {
      const {data: res} = await flowerApi.search(this.page, this.pageSize, this.flowerSearch)

      console.log(res)
      if (res.code === 200) {
        this.flowerList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },

    addFlower() {
      this.title = "添加花花"
      this.flower = {}
      this.dialogFormVisible = true
    },

    saveFlower() {
      this.$refs.ruleForm.validate(async valid => {
        let url = "/flower/add"
        let method = "post"
        if(this.flower.flowerId){
          url = "/flower/update"
          method = "put"
        }

        if (valid) {
          const {data:res} = await flowerApi.save(url,method,this.flower)
          console.log("res:",res)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {

                this.dialogFormVisible = false
                this.search()
              }
            })
          }else{
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },

    handleSizeChange(val) {
      this.pageSize = val
      // this.findByPage()
      this.search()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page = val
      this.search()
      console.log(`当前页: ${val}`);
    },
    handleEdit(index, row) {

      this.title = '修改花朵'

      this.flower = row

      this.dialogFormVisible = true

      console.log(index, row);
    },

    handleDelete(index, row) {
      this.flowerId = []
      if(row){
        this.flowerId.push(row.flowerId)
      }else{
        this.flowerId = this.multipleSelection.map(m => m.flowerId)
      }
      this.$confirm(`是否真的要删除编号为${this.flowerId}的花朵吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        flowerApi.deleteFlower(this.flowerId)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {

                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style>

#app {
  display: flex;
  justify-content: center;
}

.el-card {
  width: 90%;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
